/**
 * Created by lee_mxue on 17/6/26.
 */
import React from "react";
import ReactDOM from "react-dom";
import { addErrorListener } from "../../lib/handleError"
import weixinShare from "../../lib/weixinShare";
import Tools from "../../lib/tools";
import AJAX from "../../lib/ajax";
import InfiniteScroll from "react-infinite-scroller";
import Dialog from "../MyPackage/components/Dialog";

require('../../lib/rem');
require('./ChooseOtherReceiver.less');
require('../../styles/common.less');
require('../../styles/lux.less')
class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isReady: false,     //是否加载页面
            keywords: '',//关键字
            current: 1, //当前页码
            agent_count: 0,  //列表总数
            agent_list: [],  //列表
            loadCount: 1,    //加载次数
        };

        this.getReceiverList = this.getReceiverList.bind(this);   //获取代收人列表
        this.SelectReceiver = this.SelectReceiver.bind(this);   //选择代收人
        this.handleEdit = this.handleEdit.bind(this);   //编辑代收人信息
        this.handleSearch = this.handleSearch.bind(this);   //搜索

    }

    componentWillMount() {
        addErrorListener()()
        //隐藏分享功能
        weixinShare.hideAll();
        //获取代收人信息
        this.getReceiverList(1, "")
    }

    componentDidMount() {
        AJAX.appendBaiduAnalysis()
        this.setState({
            isReady: true,     //是否加载页面
        });
    }

    //获取代收人列表
    getReceiverList(current, keywords) {

        var _this = this;
        this.setState({
            current: current,
            keywords: keywords,
        })
        var params = {
            keywords: keywords,
            page: current,
            psize: 10,
        }

        //真实数据
        AJAX.request("agent_list", params, (data) => {
            if (data.code == 0) {
                if (current == 1) {
                    _this.setState({
                        isReady: true,     //是否可以加载页面
                        agent_count: data.body.count,
                        agent_list: data.body.list,
                        loadCount: Math.ceil(data.body.count / 10)    //获取总页数（psize == 10）
                    })
                } else {
                    _this.setState({
                        isReady: true,     //是否可以加载页面
                        agent_count: data.body.count,
                        agent_list: _this.state.agent_list.concat(data.body.list),
                        loadCount: Math.ceil(data.body.count / 10)    //获取总页数（psize == 10）
                    })
                }
            }
        })
    }

    //加载更多
    loadMoreData(current) {
        var _current = current + 1;
        var _this = this;
        //判断加载次数
        if (this.state.loadCount) {
            if (_current < _this.state.loadCount || _current == _this.state.loadCount) {
                _this.getReceiverList(_current, _this.state.keywords)
            } else {
                // alert("没有数据了！！！")
            }
        }
    }

    //搜索
    handleSearch(e) {
        var value = e.target.value;
        this.setState({
            keywords: value
        })
        //获取代收人信息
        this.getReceiverList(1, value)

    }

    //选择代收人
    SelectReceiver(data) {
        const order_id = Tools.getParams().order_id;
        Dialog.confirm({
            title: "提示",
            content: "即将向您指定的代收人发送如下信息：【近邻宝】：您好，您的好友135xxxxxx请您帮ta代取一个重要快件。取件地址为：公司前台近邻宝宝14号箱门，取件密码为xxxxxx。......",
            remarks: "【注意：发送后，您自己将无法使用“一键开箱”取件】",
            okText: "确认",
            cancelText: "取消",
            onOK: () => {
                AJAX.request("order_agent", {
                    order_id: order_id,
                    agent_id: data.id,
                }, (data) => {
                    if (data.code == 0) {
                        const wx_type = window.localStorage.getItem('wx_type');
                        window.location.href = `./PickUp?wx_type=${wx_type}&order_id=${order_id}`;   //返回首页
                        // window.location.href = "./PickUp?order_id=" + order_id;
                    }
                })
            },
            onCancel: () => {
            }
        })
    }

    //编辑代收人
    handleEdit(item) {
        const order_id = Tools.getParams().order_id;
        const ad_id = Tools.getParams().aditem_id;
        //将代收人信息存入local storage
        window.localStorage.setItem("otherReceiverData_x", JSON.stringify(item))
        window.location.href = "./EditOtherReceiver?order_id=" + order_id + "&aditem_id=" + ad_id;

    }

    render() {
        const loader = <div className="loader"></div>
        return (
            this.state.isReady &&
            <div className="main">
                <div className="top_active flex">
                    <input className="flex1 iconfont" placeholder="&#xe679;请输入姓名或手机号" type="text"
                        onChange={this.handleSearch} />
                </div>
                <div className="h3">选择好友代收</div>

                <div className="center_content addressList borderT">
                    <InfiniteScroll
                        pageStart={0}
                        threshold={5}
                        loadMore={this.loadMoreData.bind(this, this.state.current)}
                        hasMore={true}
                        useWindow={false}
                        loader={loader}
                    >
                        {
                            this.state.agent_list.map(item => {
                                return (

                                    <div className="addressItem flex">
                                        <div className="flex1" onClick={this.SelectReceiver.bind(this, item)}>
                                            <p>{item.name}</p>
                                            <p className="">{item.phone}</p>
                                        </div>
                                        <i className="iconfont iconY icon-bianji1"
                                            onClick={this.handleEdit.bind(this, item)} />
                                    </div>)
                            })
                        }
                    </InfiniteScroll>

                </div>


                <div className="bottom_submit">
                    <a className="weui-btn weui-btn_primary"
                        onClick={this.handleEdit.bind(this, {})}
                        href="javascript:;"
                        id="showTooltips"><i className="iconfont  icon-tianjia2" /> 新增联系人</a>
                </div>
            </div>

        )
    }
}
ReactDOM.render(<App />, document.getElementById('app'));
if (module.hot) {
    module.hot.accept();
}